package zhuzx.solution;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.zhuzx.util.NetUtil;

public class StressTestInvoker {
	
	public static void main(String[] args) {
		xphoneInvoking();
	}
	
	private static final String[][] envs = {
			{"http://10.248.58.175:8081/", "CRMYS200", "666666aA"},
			{"", "crmys2", "123456aAa"}
	};
	
	private static final String[] env = envs[0];
	
	static final String LOGIN_METHOD = "crm.mobile.user.login";
	static final String LOGIN_JSON = "{\"username\":\"" + env[1] + "\",\"password\":\"" + env[2] + "\"}";
	
	private static final String[][] examples = {
			{"crm.mobile.salesman.checkJobList", "18ed16cb98ee49d28ced1169ecbc2f6a", "{\"pageNo\":1,\"pageSize\":10,\"searchKey\":\"\",\"adoptStatus\":\"0\"}"},
//			{"crm.mobile.statisticInfo.realTime", "a92875bb1f8347638d1062e679b45528", "{\"customerNo\":\"0001066322\",\"pageNo\":\"\",\"year\":\"\"}"}
	};
	
	private static final List<Runnable> targets = createTargetUrls();
	
	private static List<Runnable> createTargetUrls() {
		List<Runnable> list = new ArrayList<>(examples.length);
		for (String[] exa : examples) {
			list.add(new Runnable() {
				@Override
				public void run() {
					String url = createUrl(exa[0], exa[1], exa[2]);
					try {
						System.out.println(NetUtil.get(url, null));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
		}
		return list;
	}
	
	private static String createUrl(String method, String sessionId, String json) {
		return env[0] + "xPhone/service?"
				+ "appkey=crm_mobile&client=Android&format=json&version=1.0&method=" + method
				+ "&sessionId=" + sessionId + "&bindObject=" + json;
	}
	
	public static void xphoneInvoking() {
		invoke(100, targets, 1000);
//		try {
//			System.out.println(NetUtil.get(createUrl(examples[0][0], examples[0][1], examples[0][2]), null));
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}
	
	
	public static void invoke(int concurrentLevel, List<Runnable> commandList, long frequency) {
		ScheduledExecutorService ses = Executors.newScheduledThreadPool(concurrentLevel * commandList.size());
		for (int i=1; i<=concurrentLevel; i++) {
			for (Runnable command : commandList) {
				ses.scheduleAtFixedRate(command, 0, frequency, TimeUnit.MILLISECONDS);
			}
		}
	}

}